/**
 * 首页主逻辑
 */
document.addEventListener('DOMContentLoaded', () => {
    // 全局变量
    const state = {
        currentPage: 1,
        hasMorePages: true,
        isLoading: false,
        currentSort: 'popular',
        wallpapers: [],
        lastScrollPosition: 0
    };
    
    // DOM元素
    const elements = {
        wallpaperGrid: document.getElementById('wallpaper-grid'),
        filterButtons: document.querySelectorAll('.filter-btn'),
        searchInput: document.getElementById('search-input'),
        searchBtn: document.getElementById('search-btn'),
        loadMore: document.getElementById('load-more')
    };
    
    /**
     * 初始化页面
     */
    function init() {
        // 加载壁纸
        loadWallpapers();
        
        // 绑定事件
        bindEvents();
        
        // 初始化懒加载
        initLazyLoading();
    }
    
    /**
     * 绑定事件处理
     */
    function bindEvents() {
        // 排序筛选按钮点击
        elements.filterButtons.forEach(btn => {
            btn.addEventListener('click', (e) => {
                const sort = e.target.dataset.sort;
                if (sort !== state.currentSort) {
                    // 更新UI
                    elements.filterButtons.forEach(btn => btn.classList.remove('active'));
                    e.target.classList.add('active');
                    
                    // 重置状态
                    state.currentSort = sort;
                    state.currentPage = 1;
                    state.hasMorePages = true;
                    state.wallpapers = [];
                    
                    // 清空并重新加载
                    elements.wallpaperGrid.innerHTML = `
                        <div class="loading-spinner">
                            <div class="spinner"></div>
                            <p>加载中...</p>
                        </div>
                    `;
                    loadWallpapers();
                }
            });
        });
        
        // 搜索按钮点击
        elements.searchBtn.addEventListener('click', () => {
            handleSearch();
        });
        
        // 搜索框回车
        elements.searchInput.addEventListener('keypress', (e) => {
            if (e.key === 'Enter') {
                handleSearch();
            }
        });
        
        // 滚动加载更多
        window.addEventListener('scroll', debounce(() => {
            if (state.isLoading || !state.hasMorePages) return;
            
            const scrollPosition = window.scrollY + window.innerHeight;
            const pageHeight = document.body.scrollHeight - 200; // 提前200px触发
            
            if (scrollPosition > pageHeight) {
                loadMoreWallpapers();
            }
            
            // 记录滚动位置
            state.lastScrollPosition = window.scrollY;
        }, 200));
        
        // 下拉刷新
        let touchStartY = 0;
        document.addEventListener('touchstart', (e) => {
            touchStartY = e.touches[0].clientY;
        }, { passive: true });
        
        document.addEventListener('touchmove', (e) => {
            if (window.scrollY === 0) {
                const touchMoveY = e.touches[0].clientY;
                const distance = touchMoveY - touchStartY;
                
                if (distance > 100) {
                    // 刷新操作
                    if (!state.isLoading) {
                        refreshWallpapers();
                    }
                }
            }
        }, { passive: true });
    }
    
    /**
     * 处理搜索操作
     */
    function handleSearch() {
        const query = elements.searchInput.value.trim();
        if (query) {
            // 记录搜索历史
            Storage.addSearchHistory(query);
            
            // 跳转到搜索结果页面
            window.location.href = `index.html?search=${encodeURIComponent(query)}`;
        }
    }
    
    /**
     * 加载壁纸列表
     */
    async function loadWallpapers() {
        // 检查是否是搜索模式
        const urlParams = new URLSearchParams(window.location.search);
        const searchQuery = urlParams.get('search');
        
        if (searchQuery) {
            await loadSearchResults(searchQuery);
            return;
        }
        
        // 标准加载模式
        state.isLoading = true;
        showLoadingIndicator();
        
        try {
            const response = await API.getWallpapers({
                page: state.currentPage,
                limit: 10,
                sort: state.currentSort
            });
            
            // 更新分页状态
            updatePaginationState(response.pagination);
            
            // 添加到壁纸列表
            state.wallpapers = [...state.wallpapers, ...response.data];
            
            // 渲染壁纸
            renderWallpapers(response.data);
        } catch (error) {
            console.error('加载壁纸失败:', error);
            showErrorMessage();
        } finally {
            state.isLoading = false;
            hideLoadingIndicator();
        }
    }
    
    /**
     * 加载搜索结果
     */
    async function loadSearchResults(query) {
        state.isLoading = true;
        showLoadingIndicator();
        
        try {
            // 更新UI状态
            elements.searchInput.value = query;
            
            const response = await API.searchWallpapers(query, state.currentPage, 10);
            
            // 更新分页状态
            updatePaginationState(response.pagination);
            
            // 添加到壁纸列表
            state.wallpapers = [...state.wallpapers, ...response.data];
            
            // 渲染壁纸
            renderWallpapers(response.data);
        } catch (error) {
            console.error('搜索壁纸失败:', error);
            showErrorMessage();
        } finally {
            state.isLoading = false;
            hideLoadingIndicator();
        }
    }
    
    /**
     * 加载更多壁纸
     */
    function loadMoreWallpapers() {
        if (state.hasMorePages && !state.isLoading) {
            state.currentPage++;
            loadWallpapers();
        }
    }
    
    /**
     * 刷新壁纸列表
     */
    function refreshWallpapers() {
        // 重置状态
        state.currentPage = 1;
        state.hasMorePages = true;
        state.wallpapers = [];
        
        // 清空容器
        elements.wallpaperGrid.innerHTML = `
            <div class="loading-spinner">
                <div class="spinner"></div>
                <p>刷新中...</p>
            </div>
        `;
        
        // 重新加载
        loadWallpapers();
    }
    
    /**
     * 更新分页状态
     */
    function updatePaginationState(pagination) {
        state.hasMorePages = pagination.current_page < pagination.total_pages;
        
        // 更新加载更多按钮状态
        if (!state.hasMorePages) {
            elements.loadMore.innerHTML = '<span>已加载全部内容</span>';
        } else {
            elements.loadMore.innerHTML = '<span>上拉加载更多</span>';
        }
    }
    
    /**
     * 渲染壁纸列表
     */
    function renderWallpapers(wallpapers) {
        // 移除加载指示器
        const loadingSpinner = elements.wallpaperGrid.querySelector('.loading-spinner');
        if (loadingSpinner) {
            loadingSpinner.remove();
        }
        
        // 创建壁纸卡片并添加到网格
        wallpapers.forEach(wallpaper => {
            const wallpaperCard = createWallpaperCard(wallpaper);
            elements.wallpaperGrid.appendChild(wallpaperCard);
        });
        
        // 重新初始化懒加载
        initLazyLoading();
    }
    
    /**
     * 创建壁纸卡片
     */
    function createWallpaperCard(wallpaper) {
        const isFavorite = Storage.isFavorite(wallpaper.id);
        
        const card = document.createElement('div');
        card.className = 'wallpaper-card';
        card.dataset.id = wallpaper.id;
        
        card.innerHTML = `
            <div class="wallpaper-actions">
                <div class="action-icon favorite ${isFavorite ? 'active' : ''}" data-id="${wallpaper.id}">
                    <img src="icon/favorite-s-${isFavorite ? 'fill' : 'line'}.svg" alt="图标" width="24" height="24">
                </div>
            </div>
            <img class="wallpaper-img lazy-image" data-src="${API.getWallpaperThumbnailUrl(wallpaper.id)}" alt="${wallpaper.category}壁纸">
            <div class="wallpaper-info">
                <div class="wallpaper-category">${getCategoryName(wallpaper.category)}</div>
            </div>
        `;
        
        // 点击壁纸跳转到详情页
        card.addEventListener('click', (e) => {
            // 避免点击收藏按钮时跳转
            if (!e.target.closest('.action-icon')) {
                Storage.addRecentlyViewed(wallpaper.id);
                window.location.href = `detail.html?id=${wallpaper.id}`;
            }
        });
        
        // 收藏按钮点击
        const favoriteBtn = card.querySelector('.action-icon.favorite');
        favoriteBtn.addEventListener('click', (e) => {
            e.stopPropagation(); // 阻止冒泡，避免触发卡片点击
            toggleFavorite(favoriteBtn);
        });
        
        return card;
    }
    
    /**
     * 切换收藏状态
     */
    async function toggleFavorite(buttonElement) {
        const wallpaperId = buttonElement.dataset.id;
        const isFavorite = buttonElement.classList.contains('active');
        
        try {
            if (isFavorite) {
                // 取消收藏
                await API.removeFromFavorites(wallpaperId);
                buttonElement.classList.remove('active');
                buttonElement.innerHTML = '<img src="icon/favorite-s-line.svg" alt="图标" width="24" height="24">';
            } else {
                // 添加收藏
                await API.addToFavorites(wallpaperId);
                buttonElement.classList.add('active');
                buttonElement.innerHTML = '<img src="icon/favorite-s-fill.svg" alt="图标" width="24" height="24">';
            }
        } catch (error) {
            console.error('操作收藏失败:', error);
        }
    }
    
    /**
     * 根据分类ID获取分类名称
     */
    function getCategoryName(categoryId) {
        const categoryMap = {
            'nature': '自然风光',
            'city': '城市建筑',
            'abstract': '抽象艺术',
            'minimal': '简约风格',
            'dark': '暗色系',
            'bright': '亮色系'
        };
        
        return categoryMap[categoryId] || categoryId;
    }
    
    /**
     * 显示加载指示器
     */
    function showLoadingIndicator() {
        // 如果不是第一页，显示在底部
        if (state.currentPage > 1) {
            elements.loadMore.innerHTML = `
                <div class="spinner" style="margin: 1rem auto;"></div>
                <span>加载中...</span>
            `;
        }
    }
    
    /**
     * 隐藏加载指示器
     */
    function hideLoadingIndicator() {
        if (state.currentPage > 1) {
            elements.loadMore.innerHTML = '<span>上拉加载更多</span>';
        }
    }
    
    /**
     * 显示错误提示
     */
    function showErrorMessage() {
        const errorMessage = document.createElement('div');
        errorMessage.className = 'error-message';
        errorMessage.textContent = '加载失败，请刷新重试';
        
        if (state.currentPage === 1) {
            elements.wallpaperGrid.innerHTML = '';
            elements.wallpaperGrid.appendChild(errorMessage);
        } else {
            elements.loadMore.innerHTML = '';
            elements.loadMore.appendChild(errorMessage);
        }
    }
    
    /**
     * 初始化图片懒加载
     */
    function initLazyLoading() {
        const lazyImages = document.querySelectorAll('.lazy-image');
        
        // 使用Intersection Observer实现懒加载
        if ('IntersectionObserver' in window) {
            const imageObserver = new IntersectionObserver((entries) => {
                entries.forEach(entry => {
                    if (entry.isIntersecting) {
                        const img = entry.target;
                        const src = img.dataset.src;
                        
                        // 创建图片对象
                        const tempImg = new Image();
                        tempImg.onload = () => {
                            img.src = src;
                            img.classList.remove('lazy-image');
                        };
                        tempImg.src = src;
                        
                        // 停止观察
                        imageObserver.unobserve(img);
                    }
                });
            }, {
                rootMargin: '50px 0px'
            });
            
            lazyImages.forEach(img => {
                imageObserver.observe(img);
            });
        } else {
            // 回退: 简单地加载所有图片
            lazyImages.forEach(img => {
                img.src = img.dataset.src;
                img.classList.remove('lazy-image');
            });
        }
    }
    
    /**
     * 防抖函数
     */
    function debounce(func, wait) {
        let timeout;
        return function() {
            const context = this;
            const args = arguments;
            clearTimeout(timeout);
            timeout = setTimeout(() => {
                func.apply(context, args);
            }, wait);
        };
    }
    
    // 初始化
    init();
}); 